<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ice.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/ice.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":3,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="图的定义和常用术语图是一系列顶点（结点）和描述顶点之间的关系边（弧）组成。图是数据元素的集合，这些数据元素相互连接形成网络。其形式化定义为：G&#x3D;（V，E）。其中，G表示图，V是顶点的集合，E是边或弧的集合。并且E可以表示为：E&#x3D;（Vi，Vj），表示顶点Vi和Vj之间有边或弧相连。">
<meta property="og:type" content="article">
<meta property="og:title" content="图算法">
<meta property="og:url" content="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9B%BE/index.html">
<meta property="og:site_name" content="严冰的博客">
<meta property="og:description" content="图的定义和常用术语图是一系列顶点（结点）和描述顶点之间的关系边（弧）组成。图是数据元素的集合，这些数据元素相互连接形成网络。其形式化定义为：G&#x3D;（V，E）。其中，G表示图，V是顶点的集合，E是边或弧的集合。并且E可以表示为：E&#x3D;（Vi，Vj），表示顶点Vi和Vj之间有边或弧相连。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gf003skpvlj30d005ejse.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gf003syyfsj30cy04lwfn.jpg">
<meta property="article:published_time" content="2020-05-30T12:50:49.000Z">
<meta property="article:modified_time" content="2020-06-08T00:57:51.991Z">
<meta property="article:author" content="yanbing">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gf003skpvlj30d005ejse.jpg">

<link rel="canonical" href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9B%BE/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>图算法 | 严冰的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="严冰的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">严冰的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9B%BE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/dog.jpg">
      <meta itemprop="name" content="yanbing">
      <meta itemprop="description" content="闲看庭前花开落，漫随天外云卷舒。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="严冰的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          图算法
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-30 20:50:49" itemprop="dateCreated datePublished" datetime="2020-05-30T20:50:49+08:00">2020-05-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-08 08:57:51" itemprop="dateModified" datetime="2020-06-08T08:57:51+08:00">2020-06-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">数据结构与算法</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="图的定义和常用术语"><a href="#图的定义和常用术语" class="headerlink" title="图的定义和常用术语"></a>图的定义和常用术语</h2><p>图是一系列顶点（结点）和描述顶点之间的关系边（弧）组成。图是数据元素的集合，这些数据元素相互连接形成网络。其形式化定义为：G=（V，E）。其中，G表示图，V是顶点的集合，E是边或弧的集合。并且E可以表示为：E=（Vi，Vj），表示顶点Vi和Vj之间有边或弧相连。</p>
<a id="more"></a>

<ul>
<li><p>顶点集：图中具有相同特性的数据元素的集合；</p>
</li>
<li><p>边（弧）：边是一对顶点间的路径，通常带箭头的边称为弧；</p>
</li>
<li><p>度：在无向图中顶点的度是指连接那个顶点的边的数目。在有向图中，每个顶点有两种类型的度（入度、出度）；</p>
</li>
<li><p>入度：指向那个顶点的边的数目；</p>
</li>
<li><p>出度：由那个顶点出发的边的数目；</p>
</li>
<li><p>权：有些图的边或弧附带有一些数据信息，这些数据信息称为边或弧的权。在实际问题中，权可以表示某种含义，比如在一个地方的交通图上，边上的权值表示该条线路的长度。</p>
</li>
<li><p>有向图：在一个图中，如果任意两顶点构成的偶对（如果存在）是有序的，那么称该图为有向图；</p>
</li>
<li><p>无向图：在一个图中，如果任意两顶点构成的偶对（如果存在）是无序的，那么称该图为无向图；</p>
</li>
<li><p>有向完全图：在一个有向图中，如果任意两个顶点之间都是有弧相连，则称该图是完全有向图；</p>
</li>
<li><p>有向完全图：在一个无向图中，如果任意两个顶点之间都是有边相连，则称该图是完全无向图；</p>
</li>
<li><p>稀疏图：有很少条边或弧的图；</p>
</li>
<li><p>稠密图：有很多条边或弧的图。</p>
</li>
</ul>
<h2 id="图的实现"><a href="#图的实现" class="headerlink" title="图的实现"></a>图的实现</h2><p>一个图的信息主要包括两部分：图中顶点的信息以及描述顶点之间的关系——边或弧的信息。</p>
<p>邻接矩阵和邻接表是图的两种最通用的存储结构。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IGraph</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">	 <span class="function"><span class="keyword">int</span> <span class="title">getNumOfVertex</span><span class="params">()</span></span>;<span class="comment">//获取顶点的个数</span></span><br><span class="line">	 <span class="function"><span class="keyword">boolean</span> <span class="title">insertVex</span><span class="params">(E v)</span></span>;<span class="comment">//插入顶点</span></span><br><span class="line">	 <span class="function"><span class="keyword">boolean</span> <span class="title">deleteVex</span><span class="params">(E v)</span></span>;<span class="comment">//删除顶点</span></span><br><span class="line">	 <span class="function"><span class="keyword">int</span> <span class="title">indexOfVex</span><span class="params">(E v)</span></span>;<span class="comment">//定位顶点的位置</span></span><br><span class="line">	 <span class="function">E <span class="title">valueOfVex</span><span class="params">(<span class="keyword">int</span> v)</span></span>;<span class="comment">// 定位指定位置的顶点</span></span><br><span class="line">	 <span class="function"><span class="keyword">boolean</span> <span class="title">insertEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2,<span class="keyword">int</span> weight)</span></span>;<span class="comment">//插入边</span></span><br><span class="line">	 <span class="function"><span class="keyword">boolean</span> <span class="title">deleteEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2)</span></span>;<span class="comment">//删除边</span></span><br><span class="line">	 <span class="function"><span class="keyword">int</span> <span class="title">getEdge</span><span class="params">(<span class="keyword">int</span> v1,<span class="keyword">int</span> v2)</span></span>;<span class="comment">//查找边</span></span><br><span class="line">	 <span class="function">String <span class="title">depthFirstSearch</span><span class="params">(<span class="keyword">int</span> v )</span></span>;<span class="comment">//深度优先搜索遍历</span></span><br><span class="line">	 <span class="function">String <span class="title">breadFirstSearch</span><span class="params">(<span class="keyword">int</span> v )</span></span>;<span class="comment">//广度优先搜索遍历</span></span><br><span class="line">	 <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span> v);<span class="comment">//最短路径</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="邻接矩阵"><a href="#邻接矩阵" class="headerlink" title="邻接矩阵"></a>邻接矩阵</h3><p>邻接矩阵是用两个数组来表示图：</p>
<ul>
<li>一个数组是一维数组，存储图中的顶点信息；</li>
<li>一个数组是二维数组，即矩阵，存储顶点之间相邻的信息，也就是边或弧的信息。</li>
</ul>
<p>如果图中有n个顶点，就需要n×n的二维数组来表示图。</p>
<p>关于权值的说明：</p>
<ul>
<li>如果图的边没有权值，用0表示顶点之间无边，用1表示顶点之间有边。</li>
<li>如果图的弧有权值，用无穷大表示顶点之间无边，用权值表示顶点之间有边，同一点之间的权值为0。</li>
</ul>
<blockquote>
<p>  注意：如果图为稀疏图的话，在用邻接矩阵表示图的时候，由于在表示边的时候会导致变成一个系数矩阵，导致很多的浪费。所以，<strong>应在图为稠密图的时候使用邻接矩阵实现图</strong>。</p>
</blockquote>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gf003skpvlj30d005ejse.jpg" alt="邻接矩阵"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GraphAdjMatrix</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">IGraph</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> E[] vexs;<span class="comment">// 存储图的顶点的一维数组</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span>[][] edges;<span class="comment">// 存储图的边的二维数组</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> numOfVexs;<span class="comment">// 顶点的实际数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> maxNumOfVexs;<span class="comment">// 顶点的最大数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">boolean</span>[] visited;<span class="comment">// 判断顶点是否被访问过</span></span><br><span class="line"> </span><br><span class="line">	<span class="comment">//构造函数</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">GraphAdjMatrix</span><span class="params">(<span class="keyword">int</span> maxNumOfVexs, Class&lt;E&gt; type)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.maxNumOfVexs = maxNumOfVexs;</span><br><span class="line">		edges = <span class="keyword">new</span> <span class="keyword">int</span>[maxNumOfVexs][maxNumOfVexs];</span><br><span class="line">		vexs = (E[]) Array.newInstance(type, maxNumOfVexs);</span><br><span class="line">	&#125;</span><br><span class="line"> 	<span class="comment">// 得到顶点的数目</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getNumOfVertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> numOfVexs;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 插入顶点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">insertVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (numOfVexs &gt;= maxNumOfVexs)</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">		vexs[numOfVexs++] = v;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 删除顶点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deleteVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (vexs[i].equals(v)) &#123;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> j = i; j &lt; numOfVexs - <span class="number">1</span>; j++) &#123;</span><br><span class="line">					vexs[j] = vexs[j + <span class="number">1</span>];</span><br><span class="line">				&#125;</span><br><span class="line">				vexs[numOfVexs - <span class="number">1</span>] = <span class="keyword">null</span>;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> col = i; col &lt; numOfVexs - <span class="number">1</span>; col++) &#123;</span><br><span class="line">					<span class="keyword">for</span> (<span class="keyword">int</span> row = <span class="number">0</span>; row &lt; numOfVexs; row++) &#123;</span><br><span class="line">						edges[col][row] = edges[col + <span class="number">1</span>][row];</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> row = i; row &lt; numOfVexs - <span class="number">1</span>; row++) &#123;</span><br><span class="line">					<span class="keyword">for</span> (<span class="keyword">int</span> col = <span class="number">0</span>; col &lt; numOfVexs; col++) &#123;</span><br><span class="line">						edges[col][row] = edges[col][row + <span class="number">1</span>];</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				numOfVexs--;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 定位顶点的位置</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indexOfVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (vexs[i].equals(v)) &#123;</span><br><span class="line">				<span class="keyword">return</span> i;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 定位指定位置的顶点</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">valueOfVex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> ||v &gt;= numOfVexs )</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">return</span> vexs[v];</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 插入边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">insertEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2, <span class="keyword">int</span> weight)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		edges[v1][v2] = weight;</span><br><span class="line">		edges[v2][v1] = weight;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 删除边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deleteEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		edges[v1][v2] = <span class="number">0</span>;</span><br><span class="line">		edges[v2][v1] = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 查找边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getEdge</span><span class="params">(<span class="keyword">int</span> v1,<span class="keyword">int</span> v2)</span></span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		<span class="keyword">return</span> edges[v1][v2];</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 深度优先搜索遍历</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">depthFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">// 广度优先搜索遍历</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">breadFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;&#125;</span><br><span class="line">	<span class="comment">// 实现Dijkstra算法</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span> v) &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="邻接表"><a href="#邻接表" class="headerlink" title="邻接表"></a>邻接表</h3><p>前面的邻接矩阵方法实际上是图的一种静态存储方法。建立这种存储结构时需要预先知道图中顶点的个数。如果图结构本身需要在解决问题的过程中动态地产生，则每增加或者删除一个顶点都需要改变邻接矩阵的大小，显然这样做的效率很低。除此之外，邻接矩阵所占用的存储单元数目至于图中的顶点的个数有关，而与边或弧的数目无关，若图是一个稀疏图的话，必然造成存储空间的浪费。邻接表很好地解决了这些问题。</p>
<p>邻接表的存储方式是一种顺序存储与链式存储相结合的存储方式，</p>
<ul>
<li>顺序存储部分用来保存图中的顶点信息，</li>
<li>链式存储部分用来保存图中边或弧的信息。</li>
</ul>
<p>具体的做法是，使用一个一维数组保存图中顶点的信息，数组中每个数组元素包含两个域。</p>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gf003syyfsj30cy04lwfn.jpg" alt="邻接表"></p>
<p>邻接表是一个数组，数组的每个元素包含顶点信息和单链表的头指针两部分。而单链表的结构分成与顶点相邻的元素信息、边的信息和下一个与顶点相邻的元素指针</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GraphAdjList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">IGraph</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">	<span class="comment">// 链表中的节点</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ENode</span> </span>&#123;</span><br><span class="line">		<span class="keyword">int</span> adjvex; <span class="comment">// 邻接顶点序号</span></span><br><span class="line">		<span class="keyword">int</span> weight;<span class="comment">// 存储边或弧相关的信息，如权值</span></span><br><span class="line">		ENode nextadj; <span class="comment">// 下一个邻接表结点</span></span><br><span class="line"> </span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">ENode</span><span class="params">(<span class="keyword">int</span> adjvex, <span class="keyword">int</span> weight)</span> </span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.adjvex = adjvex;</span><br><span class="line">			<span class="keyword">this</span>.weight = weight;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 数组中的节点</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">VNode</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">		E data; <span class="comment">// 顶点信息</span></span><br><span class="line">		ENode firstadj; <span class="comment">// //邻接表的第1个结点</span></span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="keyword">private</span> VNode&lt;E&gt;[] vexs; <span class="comment">// 顶点数组</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> numOfVexs;<span class="comment">// 顶点的实际数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> maxNumOfVexs;<span class="comment">// 顶点的最大数量</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">boolean</span>[] visited;<span class="comment">// 判断顶点是否被访问过</span></span><br><span class="line"> </span><br><span class="line">	<span class="comment">//构造函数</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">GraphAdjList</span><span class="params">(<span class="keyword">int</span> maxNumOfVexs)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.maxNumOfVexs = maxNumOfVexs;</span><br><span class="line">		vexs = (VNode&lt;E&gt;[]) Array.newInstance(VNode<span class="class">.<span class="keyword">class</span>, <span class="title">maxNumOfVexs</span>)</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 得到顶点的数目</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getNumOfVertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> numOfVexs;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 插入顶点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">insertVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (numOfVexs &gt;= maxNumOfVexs)</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">		VNode&lt;E&gt; vex = <span class="keyword">new</span> VNode&lt;E&gt;();</span><br><span class="line">		vex.data = v;</span><br><span class="line">		vexs[numOfVexs++] = vex;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 删除顶点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deleteVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (vexs[i].data.equals(v)) &#123;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> j = i; j &lt; numOfVexs - <span class="number">1</span>; j++) &#123;</span><br><span class="line">					vexs[j] = vexs[j + <span class="number">1</span>];</span><br><span class="line">				&#125;</span><br><span class="line">				vexs[numOfVexs - <span class="number">1</span>] = <span class="keyword">null</span>;</span><br><span class="line">				numOfVexs--;</span><br><span class="line">				ENode current;</span><br><span class="line">				ENode previous;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; numOfVexs; j++) &#123;</span><br><span class="line">					<span class="keyword">if</span> (vexs[j].firstadj == <span class="keyword">null</span>)</span><br><span class="line">						<span class="keyword">continue</span>;</span><br><span class="line">					<span class="keyword">if</span> (vexs[j].firstadj.adjvex == i) &#123;</span><br><span class="line">						vexs[j].firstadj = <span class="keyword">null</span>;</span><br><span class="line">						<span class="keyword">continue</span>;</span><br><span class="line">					&#125;</span><br><span class="line">					current = vexs[j].firstadj;</span><br><span class="line">					<span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">						previous = current;</span><br><span class="line">						current = current.nextadj;</span><br><span class="line">						<span class="keyword">if</span> (current != <span class="keyword">null</span> &amp;&amp; current.adjvex == i) &#123;</span><br><span class="line">							previous.nextadj = current.nextadj;</span><br><span class="line">							<span class="keyword">break</span>;</span><br><span class="line">						&#125;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; numOfVexs; j++) &#123;</span><br><span class="line">					current = vexs[j].firstadj;</span><br><span class="line">					<span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">						<span class="keyword">if</span> (current.adjvex &gt; i)</span><br><span class="line">							current.adjvex--;</span><br><span class="line">						current = current.nextadj;</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 定位顶点的位置</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indexOfVex</span><span class="params">(E v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">			<span class="keyword">if</span> (vexs[i].data.equals(v)) &#123;</span><br><span class="line">				<span class="keyword">return</span> i;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 定位指定位置的顶点</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> E <span class="title">valueOfVex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">return</span> vexs[v].data;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 插入边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">insertEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2, <span class="keyword">int</span> weight)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		ENode vex1 = <span class="keyword">new</span> ENode(v2, weight);</span><br><span class="line"> </span><br><span class="line">		<span class="comment">// 索引为index1的顶点没有邻接顶点</span></span><br><span class="line">		<span class="keyword">if</span> (vexs[v1].firstadj == <span class="keyword">null</span>) &#123;</span><br><span class="line">			vexs[v1].firstadj = vex1;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 索引为index1的顶点有邻接顶点</span></span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			vex1.nextadj = vexs[v1].firstadj;</span><br><span class="line">			vexs[v1].firstadj = vex1;</span><br><span class="line">		&#125;</span><br><span class="line">		ENode vex2 = <span class="keyword">new</span> ENode(v1, weight);</span><br><span class="line">		<span class="comment">// 索引为index2的顶点没有邻接顶点</span></span><br><span class="line">		<span class="keyword">if</span> (vexs[v2].firstadj == <span class="keyword">null</span>) &#123;</span><br><span class="line">			vexs[v2].firstadj = vex2;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 索引为index1的顶点有邻接顶点</span></span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			vex2.nextadj = vexs[v2].firstadj;</span><br><span class="line">			vexs[v2].firstadj = vex2;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 删除边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deleteEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		<span class="comment">// 删除索引为index1的顶点与索引为index2的顶点之间的边</span></span><br><span class="line">		ENode current = vexs[v1].firstadj;</span><br><span class="line">		ENode previous = <span class="keyword">null</span>;</span><br><span class="line">		<span class="keyword">while</span> (current != <span class="keyword">null</span> &amp;&amp; current.adjvex != v2) &#123;</span><br><span class="line">			previous = current;</span><br><span class="line">			current = current.nextadj;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (current != <span class="keyword">null</span>)</span><br><span class="line">			previous.nextadj = current.nextadj;</span><br><span class="line">		<span class="comment">// 删除索引为index2的顶点与索引为index1的顶点之间的边</span></span><br><span class="line">		current = vexs[v2].firstadj;</span><br><span class="line">		<span class="keyword">while</span> (current != <span class="keyword">null</span> &amp;&amp; current.adjvex != v1) &#123;</span><br><span class="line">			previous = current;</span><br><span class="line">			current = current.nextadj;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (current != <span class="keyword">null</span>)</span><br><span class="line">			previous.nextadj = current.nextadj;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 查找边</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getEdge</span><span class="params">(<span class="keyword">int</span> v1, <span class="keyword">int</span> v2)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (v1 &lt; <span class="number">0</span> || v2 &lt; <span class="number">0</span> || v1 &gt;= numOfVexs || v2 &gt;= numOfVexs)</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">		ENode current = vexs[v1].firstadj;</span><br><span class="line">		<span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">if</span> (current.adjvex == v2) &#123;</span><br><span class="line">				<span class="keyword">return</span> current.weight;</span><br><span class="line">			&#125;</span><br><span class="line">			current = current.nextadj;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 深度优先搜索遍历</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">depthFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 广度优先搜索遍历</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">breadFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;&#125;</span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 实现Dijkstra算法</span></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span> v) &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="图的遍历"><a href="#图的遍历" class="headerlink" title="图的遍历"></a>图的遍历</h2><p>图的遍历是指从图中的任一顶点出发，对图中的所有顶点访问一次并且只访问一次。图的遍历是图的一种基本操作，图中的许多其他操作也都是建立在遍历的基础之上。在图中，没有特殊的顶点被指定为起始顶点，图的遍历可以从任何顶点开始。</p>
<h3 id="深度优先搜索算法"><a href="#深度优先搜索算法" class="headerlink" title="深度优先搜索算法"></a>深度优先搜索算法</h3><p><strong>算法的思想</strong></p>
<p>从图中的某一个顶点x出发，访问x，然后遍历任何一个与x相邻的未被访问的顶点y，再遍历任何一个与y相邻的未被访问的顶点z……依次类推，直到到达一个所有邻接点都被访问的顶点为止；然后，依次回退到尚有邻接点未被访问过的顶点，重复上述过程，直到图中的全部顶点都被访问过为止。</p>
<p><strong>算法实现的思想</strong></p>
<p>深度优先遍历背后基于堆栈，有两种方式：</p>
<ul>
<li>第一种是在程序中<strong>显示构造堆栈</strong>，利用压栈出栈操作实现；</li>
<li>第二种是利用<strong>递归函数调用</strong>，基于递归程序栈实现。</li>
</ul>
<p>本文介绍第一种方式：</p>
<ol>
<li>访问起始顶点，并将其压入栈中；</li>
<li>从栈中弹出最上面的顶点，将与其相邻的未被访问的顶点压入栈中；</li>
<li>重复第二步，直至栈为空栈。</li>
</ol>
<p>未被访问的顶点怎么识别呢？利用visited数组来进行标记。</p>
<p><strong>算法的实现</strong></p>
<p>基于邻接矩阵的算法实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">depthFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    visited = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];</span><br><span class="line">    StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;Integer&gt;();</span><br><span class="line">    stack.push(v);</span><br><span class="line">    visited[v] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">        v = stack.pop();</span><br><span class="line">        sb.append(vexs[v] + <span class="string">","</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = numOfVexs - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">            <span class="keyword">if</span> (edges[v][i] != <span class="number">0</span> &amp;&amp; edges[v][i] != Integer.MAX_VALUE &amp;&amp; !visited[i]) &#123;</span><br><span class="line">                stack.push(i);</span><br><span class="line">                visited[i] = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sb.length() &gt; <span class="number">0</span> ? sb.substring(<span class="number">0</span>, sb.length() - <span class="number">1</span>) : <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>基于邻接表的算法实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">depthFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    visited = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];</span><br><span class="line">    StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;Integer&gt;();</span><br><span class="line">    stack.push(v);</span><br><span class="line">    visited[v] = <span class="keyword">true</span>;</span><br><span class="line">    ENode current;</span><br><span class="line">    <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">        v = stack.pop();</span><br><span class="line">        sb.append(vexs[v].data + <span class="string">","</span>);</span><br><span class="line">        current = vexs[v].firstadj;</span><br><span class="line">        <span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!visited[current.adjvex]) &#123;</span><br><span class="line">                stack.push(current.adjvex);</span><br><span class="line">                visited[current.adjvex] = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            current = current.nextadj;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sb.length() &gt; <span class="number">0</span> ? sb.substring(<span class="number">0</span>, sb.length() - <span class="number">1</span>) : <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="广度优先搜索算法"><a href="#广度优先搜索算法" class="headerlink" title="广度优先搜索算法"></a>广度优先搜索算法</h3><p><strong>算法的思想</strong></p>
<p>从图中的某一个顶点x出发，访问x，然后访问与x所相邻的所有未被访问的顶点x1、x2……xn，接着再依次访问与x1、x2……xn相邻的未被访问的所有顶点。依次类推，直至图中的每个顶点都被访问。</p>
<p><strong>算法实现的思想</strong></p>
<p>广度优先遍历背后基于<strong>队列</strong>，下面介绍一下具体实现的方法：</p>
<ol>
<li>访问起始顶点，并将插入队列；</li>
<li>从队列中删除队头顶点，将与其相邻的未被访问的顶点插入队列中；</li>
<li>重复第二步，直至队列为空。</li>
</ol>
<p>未被访问的顶点怎么识别呢？利用visited数组来进行标记。</p>
<p><strong>算法的实现</strong></p>
<p>基于邻接矩阵的算法实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">breadFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    visited = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];</span><br><span class="line">    StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    Queue&lt;Integer&gt; queue = <span class="keyword">new</span> LinkedList&lt;Integer&gt;();</span><br><span class="line">    queue.offer(v);</span><br><span class="line">    visited[v] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        v = queue.poll();</span><br><span class="line">        sb.append(vexs[v] + <span class="string">","</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (edges[v][i] != <span class="number">0</span> &amp;&amp; edges[v][i] != Integer.MAX_VALUE &amp;&amp; !visited[i]) &#123;</span><br><span class="line">                queue.offer(i);</span><br><span class="line">                visited[i] = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sb.length() &gt; <span class="number">0</span> ? sb.substring(<span class="number">0</span>, sb.length() - <span class="number">1</span>) : <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>基于邻接表的算法实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">breadFirstSearch</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    visited = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];</span><br><span class="line">    StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    Queue&lt;Integer&gt; queue = <span class="keyword">new</span> LinkedList&lt;Integer&gt;();</span><br><span class="line">    queue.offer(v);</span><br><span class="line">    visited[v] = <span class="keyword">true</span>;</span><br><span class="line">    ENode current;</span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        v = queue.poll();</span><br><span class="line">        sb.append(vexs[v].data + <span class="string">","</span>);</span><br><span class="line">        current = vexs[v].firstadj;</span><br><span class="line">        <span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!visited[current.adjvex]) &#123;</span><br><span class="line">                queue.offer(current.adjvex);</span><br><span class="line">                visited[current.adjvex] = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            current = current.nextadj;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sb.length() &gt; <span class="number">0</span> ? sb.substring(<span class="number">0</span>, sb.length() - <span class="number">1</span>) : <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="最短路径"><a href="#最短路径" class="headerlink" title="最短路径"></a>最短路径</h2><p>最短路径的问题是比较典型的应用问题。在图中，确定了起始点和终点之后，一般情况下都可以有很多条路径来连接两者。而边或弧的权值最小的那一条路径就称为两点之间的最短路径，路径上的第一个顶点为源点，最后一个顶点为终点。</p>
<h3 id="Dijkstra算法"><a href="#Dijkstra算法" class="headerlink" title="Dijkstra算法"></a>Dijkstra算法</h3><p><strong>算法特点</strong></p>
<p>Dijkstra算法使用了<strong>广度优先搜索</strong>解决赋权<strong>有向图</strong>或者<strong>无向图</strong>的<strong>单源最短路径</strong>问题，算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。</p>
<p>该算法的时间复杂度是n^2^，可以使用堆优化。</p>
<p>但是要注意一点，Dijkstra算法只能适用于权值为正的情况下；如果权值存在负数，则不能使用。</p>
<p><strong>算法思想</strong></p>
<ol>
<li>设置两个顶点集S和T，集合S中存放已经找到最短路径的顶点，集合T中存放着当前还未找到最短路径的顶点；</li>
<li>初始状态下，集合S中只包含源点V1，T中为除了源点之外的其余顶点，此时源点到各顶点的最短路径为两个顶点所连的边上的权值，如果源点V1到该顶点没有边，则最小路径为无穷大；</li>
<li>从集合T中选取到源点V1的路径长度最短的顶点Vi加入到集合S中；</li>
<li>修改源点V1到集合T中剩余顶点Vj的最短路径长度。新的最短路径长度值为Vj原来的最短路径长度值与顶点Vi的最短路径长度加上Vi到Vj的路径长度值中的较小者；</li>
<li>不断重复步骤3、4，直至集合T的顶点全部加入到集合S中。</li>
</ol>
<p>由此分析下来，我们可以得到以下几点：</p>
<ul>
<li><p>需要设立两个数组：</p>
<p>一个数组为diatance，用于存放个顶点距离源点的距离；</p>
<p>另一个数组为st，用于判断顶点是在哪一个集合内（true为在S集合，false为在T集合内）。</p>
</li>
<li><p>Dijkstra算法的精髓：</p>
<p>每次循环都将T集合内距离源点最近的那个点加入到S集合中，且加入的那个点距离源点的距离由“最短距离估计值”转变成“最短距离准确值”；</p>
<p>每次循环添加一个点到S集合中后，会导致与加入的那个点相邻的顶点可能会发生距离的更新，也就是“最短距离估计值”的更新。更新方法是取原本的“最短距离估计值”与新加入的那个点的“最短距离确定值”+新加入的那个点与其邻点的距离的较小者。</p>
<p>“最短距离估计值”的真正内涵：其实可以把S集合看成一个黑箱子，“最短距离估计值”就是该顶点经过黑箱子里的各个点到源点的最短距离，但不能保证该顶点是否可以通过黑箱子外（T集合）的顶点绕路达到更短。只有每次循环中“最短距离估计值”中的最小值，才能确定为“最短距离确定值”加入到集合S。</p>
</li>
</ul>
<p><strong>算法实现</strong></p>
<p>基于邻接矩阵的代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span> v) &#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    <span class="keyword">boolean</span>[] st = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];<span class="comment">// 默认初始为false</span></span><br><span class="line">    <span class="keyword">int</span>[] distance = <span class="keyword">new</span> <span class="keyword">int</span>[numOfVexs];<span class="comment">// 存放源点到其他点的矩离</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++)&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = i + <span class="number">1</span>; j &lt; numOfVexs; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (edges[i][j] == <span class="number">0</span>) &#123;</span><br><span class="line">                edges[i][j] = Integer.MAX_VALUE;</span><br><span class="line">                edges[j][i] = Integer.MAX_VALUE;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">        distance[i] = edges[v][i];</span><br><span class="line">    &#125;</span><br><span class="line">    st[v] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">// 处理从源点到其余顶点的最短路径</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; ++i) &#123;</span><br><span class="line">        <span class="keyword">int</span> min = Integer.MAX_VALUE;</span><br><span class="line">        <span class="keyword">int</span> index = -<span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 比较从源点到其余顶点的路径长度</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; numOfVexs; ++j) &#123;</span><br><span class="line">            <span class="comment">// 从源点到j顶点的最短路径还没有找到</span></span><br><span class="line">            <span class="keyword">if</span> (st[j]==<span class="keyword">false</span>) &#123;</span><br><span class="line">                <span class="comment">// 从源点到j顶点的路径长度最小</span></span><br><span class="line">                <span class="keyword">if</span> (distance[j] &lt; min) &#123;</span><br><span class="line">                    index = j;</span><br><span class="line">                    min = distance[j];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//找到源点到索引为index顶点的最短路径长度</span></span><br><span class="line">        <span class="keyword">if</span>(index != -<span class="number">1</span>)&#123;</span><br><span class="line">            st[index] = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 更新当前最短路径及距离</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w = <span class="number">0</span>; w &lt; numOfVexs; w++)&#123;</span><br><span class="line">            <span class="keyword">if</span> (st[w] == <span class="keyword">false</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (edges[index][w] != Integer.MAX_VALUE</span><br><span class="line">                    &amp;&amp; (min + edges[index][w] &lt; distance[w]))</span><br><span class="line">                    distance[w] = min + edges[index][w];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> distance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>基于邻接表的代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[] dijkstra(<span class="keyword">int</span> v) &#123;</span><br><span class="line">    <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= numOfVexs)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ArrayIndexOutOfBoundsException();</span><br><span class="line">    <span class="keyword">boolean</span>[] st = <span class="keyword">new</span> <span class="keyword">boolean</span>[numOfVexs];<span class="comment">// 默认初始为false</span></span><br><span class="line">    <span class="keyword">int</span>[] distance = <span class="keyword">new</span> <span class="keyword">int</span>[numOfVexs];<span class="comment">// 存放源点到其他点的距离</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">        distance[i] = Integer.MAX_VALUE;</span><br><span class="line">    &#125;</span><br><span class="line">    ENode current;</span><br><span class="line">    current = vexs[v].firstadj;</span><br><span class="line">    <span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">        distance[current.adjvex] = current.weight;</span><br><span class="line">        current = current.nextadj;</span><br><span class="line">    &#125;</span><br><span class="line">    distance[v] = <span class="number">0</span>;</span><br><span class="line">    st[v] = <span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">// 处理从源点到其余顶点的最短路径</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numOfVexs; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> min = Integer.MAX_VALUE;</span><br><span class="line">        <span class="keyword">int</span> index = -<span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 比较从源点到其余顶点的路径长度</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; numOfVexs; j++) &#123;</span><br><span class="line">            <span class="comment">// 从源点到j顶点的最短路径还没有找到</span></span><br><span class="line">            <span class="keyword">if</span> (st[j] == <span class="keyword">false</span>) &#123;</span><br><span class="line">                <span class="comment">// 从源点到j顶点的路径长度最小</span></span><br><span class="line">                <span class="keyword">if</span> (distance[j] &lt; min) &#123;</span><br><span class="line">                    index = j;</span><br><span class="line">                    min = distance[j];</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 找到源点到索引为index顶点的最短路径长度</span></span><br><span class="line">        <span class="keyword">if</span> (index != -<span class="number">1</span>)&#123;</span><br><span class="line">            st[index] = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 更新当前最短路径及距离</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w = <span class="number">0</span>; w &lt; numOfVexs; w++)&#123;</span><br><span class="line">            <span class="keyword">if</span> (st[w] == <span class="keyword">false</span>) &#123;</span><br><span class="line">                current = vexs[w].firstadj;</span><br><span class="line">                <span class="keyword">while</span> (current != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (current.adjvex == w)&#123;</span><br><span class="line">                        <span class="keyword">if</span> (min + current.weight &lt; distance[w]) &#123;</span><br><span class="line">                            distance[w] = min + current.weight;</span><br><span class="line">                            <span class="keyword">break</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;  </span><br><span class="line">                    current = current.nextadj;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> distance;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yanbing
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9B%BE/" title="图算法">http://yoursite.com/2020/05/30/数据结构与算法/图/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="prev" title="基本数据结构">
      <i class="fa fa-chevron-left"></i> 基本数据结构
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91/" rel="next" title="二叉树">
      二叉树 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#图的定义和常用术语"><span class="nav-number">1.</span> <span class="nav-text">图的定义和常用术语</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#图的实现"><span class="nav-number">2.</span> <span class="nav-text">图的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#邻接矩阵"><span class="nav-number">2.1.</span> <span class="nav-text">邻接矩阵</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#邻接表"><span class="nav-number">2.2.</span> <span class="nav-text">邻接表</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#图的遍历"><span class="nav-number">3.</span> <span class="nav-text">图的遍历</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#深度优先搜索算法"><span class="nav-number">3.1.</span> <span class="nav-text">深度优先搜索算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#广度优先搜索算法"><span class="nav-number">3.2.</span> <span class="nav-text">广度优先搜索算法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最短路径"><span class="nav-number">4.</span> <span class="nav-text">最短路径</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Dijkstra算法"><span class="nav-number">4.1.</span> <span class="nav-text">Dijkstra算法</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yanbing"
      src="/images/dog.jpg">
  <p class="site-author-name" itemprop="name">yanbing</p>
  <div class="site-description" itemprop="description">闲看庭前花开落，漫随天外云卷舒。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">59</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yanbingzn" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yanbingzn" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/i_silence" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;i_silence" rel="noopener" target="_blank"><i class="fab fa-codiepie fa-fw"></i>CSDN</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="http://www.beian.miit.gov.cn/" rel="noopener" target="_blank">豫ICP备20019377号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yanbing</span>
</div>

<span id="busuanzi_container_site_uv">
  本站访问次数：<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
</span>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  


  
  <script type="text/javascript"
color="0,0,188" opacity='0.5' zIndex="-1" count="120" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</body>
</html>
